package com.jt.www.common.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.jt.www.admin.user.service.RegisterCustomerService;
import com.jt.www.biz.order_pc.service.SxApplicationFormService;
import com.jt.www.common.service.AttrConfigService;
import com.jt.www.dao.mapper.endorse.SaveEndorseParamMapper;
import com.jt.www.dao.mapper.issue.mapper.IssuePolicyLogEntityMapper;
import com.jt.www.dao.mapper.issue.mapper.MqMessageEntityMapper;
import com.jt.www.dao.mapper.market.MarketerInfoMapper;
import com.jt.www.dao.mapper.offline.OfflinePolicyMapper;
import com.jt.www.dao.mapper.woxuebao.InsBatchEntityMapper;
import com.jt.www.dao.mapper.woxuebao.PayRecordEntityMapper;
import com.jt.www.domain.dto.OfflineRegisterDTO;
import com.jt.www.domain.enums.common.IsOrNotEnum;
import com.jt.www.domain.po.MarketerInfoEntity;
import com.jt.www.domain.po.OfflinePolicy;
import com.jt.www.domain.qo.AddSaveEndorseParam;
import com.jt.www.domain.vo.OfflineRegisterVo;
import com.jt.www.enums.woxuebao.HandlerStatusEnum;
import com.jt.www.exception.BizException;
import com.jt.www.model.issue.entity.MqMessageEntity;
import com.jt.www.model.param.endorse.SaveEndorseParam;
import com.jt.www.model.registerCustomer.vo.ManagerInfoVo;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.sxappform.SxApplicationFormInfo;
import com.jt.www.model.woxuebao.InsBatchEntity;
import com.jt.www.model.woxuebao.TOrderChargeQueryVO;
import com.jt.www.queue.issue.ElecPolicyMsglistener;
import com.jt.www.remote.UserClient;
import com.jt.www.remote.woxuebao.InsOrderClient;
import com.jt.www.util.DateUtils;
import com.jt.www.util.JsonUtil;
import com.jt.www.util.JsonUtils;
import com.jt.www.util.RedisUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "test")
public class TestController extends BaseController {

    public static final Logger log = LoggerFactory.getLogger(TestController.class);
    private static final List<String> notStartWith = new ArrayList() {{
        add("/ads");
        add("/news");
        add("/v2");
        add("/swagger-resources");
        add("/test");
        add("/error");
    }};
    @Resource
    ElecPolicyMsglistener elecPolicyMsglistener;
    @Autowired
    IssuePolicyLogEntityMapper issuePolicyLogEntityMapper;
    @Autowired
    MqMessageEntityMapper mqMessageEntityMapper;
    @Autowired
    UserClient userClient;
    @Autowired
    SaveEndorseParamMapper saveEndorseParamMapper;
    @Autowired
    MarketerInfoMapper marketerInfoMapper;
    @Autowired
    OfflinePolicyMapper offlinePolicyMapper;
    @Autowired
    AttrConfigService attrConfigService;
    @Autowired
    RegisterCustomerService registerCustomerService;
    @Autowired
    SxApplicationFormService sxApplicationFormService;
    @Autowired
    InsBatchEntityMapper insBatchEntityMapper;
    @Autowired
    WebApplicationContext applicationContext;
    @Autowired
    PayRecordEntityMapper payRecordEntityMapper;
    @Autowired
    InsOrderClient insOrderClient;

    /**
     * 处理消息队列出错 消息未处理 或处理部分的异常情况
     *
     * @param ids
     * @throws Exception
     */
    @ApiOperation(value = "处理消息队列出错 消息未处理 或处理部分的异常情况", notes = "处理消息队列出错 消息未处理 或处理部分的异常情况", httpMethod = "GET")
    @GetMapping(value = "/processMessage", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void processMessage(String ids) throws Exception {

        List<MqMessageEntity> list = mqMessageEntityMapper.selectByIds(ids);
        for (MqMessageEntity mqMessageEntity : list) {
            Document document = DocumentHelper.parseText(mqMessageEntity.getMessage());
            try {
                elecPolicyMsglistener.processMqMessage(document.getRootElement(), mqMessageEntity.getIfCode(), System.currentTimeMillis());
            } catch (Exception e) {
                log.error("id为 { }的消息重试失败", mqMessageEntity.getId());
                e.printStackTrace();
            }
        }
    }

    @ApiOperation(value = "导出教保网所有的备注以及接口名", notes = "导出教保网所有的备注以及接口名", httpMethod = "GET")
    @GetMapping(value = "/export/notes", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericDataResponse<List>> exportNotes() {
        List<String> urls = urls(false, null, notStartWith);
        urls.add("" + urls.size());
        return GenericDataResponse.okWithData(urls);
    }

    public List<String> urls(boolean isIncludeQueryType, List<String> startWiths, List<String> notStartWiths) {
        RequestMappingHandlerMapping mapping = applicationContext
                .getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping
                .getHandlerMethods();
        List<String> sysUrls = new ArrayList<>();
        HashMap<String, String> urlMap = new HashMap<>();
        for (RequestMappingInfo info : map.keySet()) {
            // 获取url的Set集合，一个方法可能对应多个url
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            HandlerMethod method = map.get(info);
            Annotation annotation = method.getMethodAnnotation(ApiOperation.class);
            if (patterns.size() > 1) {
                throw new BizException(info.getName() + " methods have pattaren more than one");
            }
            String url = (String) ((patterns.toArray())[0]);
            if (!StringUtils.isEmpty(urlMap.get(url))) {
                continue;
            }
            if (!CollectionUtils.isEmpty(startWiths) && !isStartWith(startWiths, url)) {
                continue;
            }
            if (!CollectionUtils.isEmpty(notStartWiths) && !isNotStartWith(notStartWiths, url)) {
                continue;
            }
            StringBuilder strvalues = new StringBuilder();
            strvalues
                    .append(url)
                    .append(",")
                    .append(isIncludeQueryType ? (info.getMethodsCondition().getMethods().toString() + ",") : "")
                    .append(annotation == null ? "" : ((ApiOperation) annotation).value());
            sysUrls.add(strvalues.toString());
            urlMap.put(url, strvalues.toString());

        }
        //     FileUtils.exportTxtPaper(sysUrls, new File("D:/urls.txt"));
        return sysUrls;
    }

    private boolean isStartWith(List<String> patterns, String key) {
        for (String pattern : patterns) {
            if (key.startsWith(pattern)) {
                return true;
            }
        }
        return false;
    }

    private boolean isNotStartWith(List<String> patterns, String key) {
        for (String pattern : patterns) {
            if (key.startsWith(pattern)) {
                return false;
            }
        }
        return true;
    }

    @ApiOperation(value = "新增清单记录表记录", notes = "新增清单记录表记录", httpMethod = "POST")
    @PostMapping(value = "/insertSaveEndorse")
    public ResponseEntity insertSaveEndorse(@RequestBody List<AddSaveEndorseParam> saveEndorseParams) {

        int num = 0;
        for (AddSaveEndorseParam param : saveEndorseParams) {

            Example example = new Example(SaveEndorseParam.class);
            example.createCriteria().andEqualTo("insuranceId", param.getInsuranceId())
                    .andEqualTo("isIns", param.getIsIns());

            List<SaveEndorseParam> list = saveEndorseParamMapper.selectByExample(example);

            if (list != null && list.size() > 0) {
                SaveEndorseParam upd = new SaveEndorseParam();
                upd.setCreateTime(new Date());
                upd.setIsDeleted(false);

                num += saveEndorseParamMapper.updateByExampleSelective(upd, example);
            } else {

                SaveEndorseParam saveEndorseParam = new SaveEndorseParam();
                BeanUtils.copyProperties(param, saveEndorseParam);
                saveEndorseParam.setCreateTime(new Date());

                num += saveEndorseParamMapper.insertSelective(saveEndorseParam);
            }
        }

        return GenericDataResponse.okWithData(num);
    }

    /**
     * 同步营销人员用户的userCode
     */
    @ApiOperation(value = "同步营销人员用户的userCode", notes = "同步营销人员用户的userCode", httpMethod = "GET")
    @GetMapping(value = "/syncMarketerUserCode", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity syncMarketerUserCode() throws Exception {
        String findCode = "syncMarketerUserCode_" + System.currentTimeMillis();
        List<MarketerInfoEntity> list = marketerInfoMapper.selectAll();
        for (MarketerInfoEntity marketerInfoEntity : list) {
            String userCode = getUserCodeByLoginId(findCode, marketerInfoEntity.getMarketerPhone());
            MarketerInfoEntity update = new MarketerInfoEntity();
            update.setUserCode(userCode);
            update.setId(marketerInfoEntity.getId());
            log.info("{} 同步增员账户信息 原userCode:{}, 新userCode:{}", findCode, marketerInfoEntity);
            marketerInfoMapper.updateByPrimaryKeySelective(update);
        }

        return GenericDataResponse.ok();
    }

    private String getUserCodeByLoginId(String findCode, String loginId) {

        String userCode = "";

        log.info("{} 同步增员账户信息 根据手机号码查询userCode mobile->{}", findCode, loginId);

        GenericDataResponse<Map<String, String>> result = userClient.queryUserIsExist(loginId);

        log.info("{} 同步增员账户信息 调用用户中心查询userCode接口返回结果->{}", findCode, JsonUtil.object2Json(result));

        if (null != result && StringUtils.equals(result.getCode(), "0000")) {
            if (StringUtils.equals(result.getData().get("isExist"), "1")) {
                userCode = result.getData().get("userCode");
            }
        }

        log.info("{} 同步增员账户信息 mobile->{}, userCode->{}", findCode, loginId, userCode);

        return userCode;
    }

    /**
     * 测试用户注册
     */
    @ApiOperation(value = "测试用户注册", notes = "测试用户注册", httpMethod = "GET")
    @GetMapping(value = "/testRegister1/{userLoginId}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity testRegister1(@ApiParam(value = "登录ID", required = true) @PathVariable String userLoginId) throws Exception {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("channelCode", "edu");
        //小程序没有密码，所以入参默认一个密码
        paramMap.put("password", "123qwe!");
        paramMap.put("userLoginId", userLoginId);
        //注册
        GenericDataResponse<String> register = userClient.register(paramMap);
        System.out.println(JSON.toJSONString(register));

        return GenericDataResponse.ok();
    }

    /**
     * 测试企业注册
     */
    @ApiOperation(value = "测试企业注册", notes = "测试企业注册", httpMethod = "GET")
    @GetMapping(value = "/testRegister2/{id}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity testRegister2(@ApiParam(value = "线下保单ID", required = true) @PathVariable Long id) throws Exception {
        OfflinePolicy offlinePolicy = offlinePolicyMapper.selectByPrimaryKey(id);
        String holderName = offlinePolicy.getHolderName();
        //注册
        OfflineRegisterDTO offlineRegisterDTO = new OfflineRegisterDTO();
        offlineRegisterDTO.setAccount("E_20080714_1001");
        offlineRegisterDTO.setLinkManName("测试员");
        offlineRegisterDTO.setLinkManPhone("18210420240");
        offlineRegisterDTO.setOrgAddress("北京");
        offlineRegisterDTO.setOrgFullName(holderName);
        offlineRegisterDTO.setProvinceCode("110109");
        try {
            GenericListResponse<OfflineRegisterVo> ret = userClient.medRecordOrgRegister(Lists.newArrayList(offlineRegisterDTO));
            //默认成功 如果不成功走异常回滚
            String holderCode = ret.getList().get(0).getUserCode();
            log.info("holderCode: {}    newHolderCode: {} account: {}", offlinePolicy.getHolderCode(), holderCode, ret.getList().get(0).getOrgCode());
        } catch (Exception e) {
            //如果不能取到 就表示注册失败
            log.error("用户名为：{},的用户注册失败!入参：{}", holderName, JSON.toJSONString(offlineRegisterDTO));
            throw new RuntimeException(holderName + "用户注册失败!");
        }

        return GenericDataResponse.ok();
    }

    /**
     * 测试生成线下userCode
     */
    @ApiOperation(value = "测试生成线下userCode", notes = "测试企业注册", httpMethod = "GET")
    @GetMapping(value = "/createOfflineUserCode", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity createOfflineUserCode() throws Exception {
        return GenericDataResponse.okWithData(attrConfigService.createOfflineUserCode());
    }

    /**
     * 测试用户是否注册
     */
    @ApiOperation(value = "测试用户是否注册", notes = "测试企业注册", httpMethod = "GET")
    @GetMapping(value = "/queryUserIsExist/{phoneNum}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity queryUserIsExist(@PathVariable String phoneNum) throws Exception {
        return GenericDataResponse.okWithData(userClient.queryUserIsExist(phoneNum));
    }

    /**
     * 测试推广人
     */
    @ApiOperation(value = "测试推广人", notes = "测试推广人", httpMethod = "GET")
    @GetMapping(value = "/testPromoter/{phoneNum}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity testPromoter(@PathVariable String phoneNum) throws Exception {

        String findCode = "testPromoter";
        InsBatchEntity insBatchEntity = new InsBatchEntity();
        //添加推广人信息
        ResponseEntity<GenericDataResponse<ManagerInfoVo>> response = registerCustomerService.queryPromoterByCustomerAccount(findCode, phoneNum);
        if (GenericDataResponse.CODE_OK.equals(response.getBody().getCode()) && null != response.getBody().getData()) {
            ManagerInfoVo managerInfoVo = response.getBody().getData();
            insBatchEntity.setMarketerUserCode(managerInfoVo.getManagerUserCode());
            insBatchEntity.setMarketerName(managerInfoVo.getManagerName());
            insBatchEntity.setMarketerNo(managerInfoVo.getMarketerNo());
            insBatchEntity.setMarketerBranchCode(managerInfoVo.getBranchCode());
            insBatchEntity.setMarketerBranchName(managerInfoVo.getBranchName());
            insBatchEntity.setMarketerChannelCode(managerInfoVo.getChannelCode());
            insBatchEntity.setMarketerChannelName(managerInfoVo.getChannelName());
            return GenericDataResponse.okWithData(insBatchEntity);
        }
        return GenericDataResponse.okWithData(null);
    }

    /**
     * 测试缓存计数
     */
    @ApiOperation(value = "测试缓存计数", notes = "测试缓存计数", httpMethod = "GET")
    @GetMapping(value = "/testRedis", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity testRedis() throws Exception {

        //设置每日最大插入限制锁
        String key = "SAVE_APP_FORM_" + DateUtils.converDate(new Date());
        String value = RedisUtil.getValue(key);
        //判断之前有没有保存过
        if (org.apache.commons.lang3.StringUtils.isBlank(value)) {
            //没有保存过 设置初始值
            RedisUtil.setLock(key, "1", 1L, TimeUnit.DAYS);
        } else if (Integer.parseInt(value) > 2) {
            RedisUtil.delete(key);
            return GenericDataResponse.errorWithMsg("保存过多");
        } else {
            RedisUtil.increment(key, 1);
        }
        return GenericDataResponse.okWithData("保存成功");
    }

    /**
     * 测试支付
     */
    @ApiOperation(value = "测试支付", notes = "测试支付", httpMethod = "GET")
    @GetMapping(value = "/testOrderPay/{id}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity testOrderPay() throws Exception {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++)
            exec.execute(new MyRunnable(insOrderClient));
        exec.shutdown();

        return GenericDataResponse.ok();
    }

    @ApiOperation(value = "业务端，下载投保单PDF2", notes = "业务端，下载投保单PDF", httpMethod = "GET")
    @GetMapping(value = "/_bai/downAppPdf2", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void downAppPdf(HttpServletRequest request, HttpServletResponse response) {
        try {
            String a = "[{\"additionalPrem\":\"4\",\"basePrem\":\"6\",\"clauseName\":\"《中国人寿财产保险股份有限公司校（园）方责任保险条款》，备案号国寿产险（备案）【2009】61号，《中国人寿财产保险股份有限公司 校（园）方责任保险附加校方无过失责任保险条款》备案号：国寿产险（备-责任）【2011】附69号\",\"endDate\":\"2021-08-31\",\"holderAddress\":\"qweriuhihi\",\"holderCityCode\":\"140400\",\"holderCityName\":\"长治市\",\"holderContacts\":\"1ipoipo\",\"holderContactsPhone\":\"13652193286\",\"holderCountyCode\":\"140423\",\"holderCountyName\":\"襄垣县\",\"holderEmail\":\"13652193286@qq.com\",\"holderName\":\"fsoaihfoi \",\"holderOrgCode\":\"132156486456453\",\"holderProvinceCode\":\"140000\",\"holderProvinceName\":\"山西省\",\"holderZipCode\":\"145624\",\"insuranceCompany\":\"中国人民财产保险股份有限公司长治市分公司\",\"insuredAddress\":\"qweriuhihi\",\"insuredCityCode\":\"140400\",\"insuredCityName\":\"长治市\",\"insuredContacts\":\"1ipoipo\",\"insuredContactsPhone\":\"13652193286\",\"insuredCountyCode\":\"140423\",\"insuredCountyName\":\"襄垣县\",\"insuredEmail\":\"13652193286@qq.com\",\"insuredName\":\"fsoaihfoi \",\"insuredOrgCode\":\"132156486456453\",\"insuredProvinceCode\":\"140000\",\"insuredProvinceName\":\"山西省\",\"insuredZipCode\":\"145624\",\"isDeleted\":false,\"isValid\":\"1\",\"productName\":\"中小学幼儿园校方责任保险\",\"sameHolder\":\"1\",\"schoolProperty\":\"edu_03\",\"schoolType\":\"edu_06\",\"startDate\":\"2020-09-01\",\"status\":\"1\"},{\"additionalPrem\":\"40万元 50元/人/年\",\"additionalPrem2\":\"10万元 10元/人/年\",\"basePrem\":\"50\",\"clauseName\":\"《中国人寿财产保险股份有限公司教职员工校方责任保险条款》(注册编号：C00010830912019081208591)、《中国人寿财产保险股份有限公司教职员工校方责任保险附加猝死责任保险条款》(注册编号：C00010830922019081208541)、《中国人寿财产保险股份有限公司教职员工校方责任保险附加其他法律赔偿责任保险条款》(注册编号：C00010830922019081208561)\",\"endDate\":\"2021-08-31\",\"holderAddress\":\"qweriuhihi\",\"holderCityCode\":\"140400\",\"holderCityName\":\"长治市\",\"holderContacts\":\"1ipoipo\",\"holderContactsPhone\":\"13652193286\",\"holderCountyCode\":\"140423\",\"holderCountyName\":\"襄垣县\",\"holderEmail\":\"13652193286@qq.com\",\"holderName\":\"fsoaihfoi \",\"holderOrgCode\":\"132156486456453\",\"holderProvinceCode\":\"140000\",\"holderProvinceName\":\"山西省\",\"holderZipCode\":\"145624\",\"insuranceCompany\":\"中国人寿财产保险股份有限公司太原市中心支公司\",\"insuredAddress\":\"qweriuhihi\",\"insuredCityCode\":\"140400\",\"insuredCityName\":\"长治市\",\"insuredContacts\":\"1ipoipo\",\"insuredContactsPhone\":\"13652193286\",\"insuredCountyCode\":\"140423\",\"insuredCountyName\":\"襄垣县\",\"insuredEmail\":\"13652193286@qq.com\",\"insuredName\":\"fsoaihfoi \",\"insuredOrgCode\":\"132156486456453\",\"insuredProvinceCode\":\"140000\",\"insuredProvinceName\":\"山西省\",\"insuredZipCode\":\"145624\",\"isDeleted\":false,\"isValid\":\"1\",\"productName\":\"中小学幼儿园教职工责任保险\",\"sameHolder\":\"1\",\"schoolProperty\":\"edu_03\",\"schoolType\":\"edu_06\",\"startDate\":\"2020-09-01\",\"status\":\"1\"}]";
            List<SxApplicationFormInfo> param = JSON.parseArray(a, SxApplicationFormInfo.class);
            sxApplicationFormService.downAppPdf(param, request, response);
        } catch (Exception e) {
            //log.error("生成投保单pdf失败,请稍后重试")xdc;
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "业务端，下载投保单PDF3", notes = "业务端，下载投保单PDF", httpMethod = "GET")
    @GetMapping(value = "/_bai/downAppPdf3", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void downAppPdf3(HttpServletRequest request, HttpServletResponse response) {
        try {
            String a = "[{\"additionalPrem\":\"4\",\"basePrem\":\"6\",\"clauseName\":\"《中国人寿财产保险股份有限公司校（园）方责任保险条款》，备案号国寿产险（备案）【2009】61号，《中国人寿财产保险股份有限公司 校（园）方责任保险附加校方无过失责任保险条款》备案号：国寿产险（备-责任）【2011】附69号\",\"endDate\":\"2021-08-31\",\"holderAddress\":\"qweriuhihi\",\"holderCityCode\":\"140400\",\"holderCityName\":\"长治市\",\"holderContacts\":\"1ipoipo\",\"holderContactsPhone\":\"13652193286\",\"holderCountyCode\":\"140423\",\"holderCountyName\":\"襄垣县\",\"holderEmail\":\"13652193286@qq.com\",\"holderName\":\"fsoaihfoi \",\"holderOrgCode\":\"132156486456453\",\"holderProvinceCode\":\"140000\",\"holderProvinceName\":\"山西省\",\"holderZipCode\":\"145624\",\"insuranceCompany\":\"中国人民财产保险股份有限公司长治市分公司\",\"insuredAddress\":\"qweriuhihi\",\"insuredCityCode\":\"140400\",\"insuredCityName\":\"长治市\",\"insuredContacts\":\"1ipoipo\",\"insuredContactsPhone\":\"13652193286\",\"insuredCountyCode\":\"140423\",\"insuredCountyName\":\"襄垣县\",\"insuredEmail\":\"13652193286@qq.com\",\"insuredName\":\"fsoaihfoi \",\"insuredOrgCode\":\"132156486456453\",\"insuredProvinceCode\":\"140000\",\"insuredProvinceName\":\"山西省\",\"insuredZipCode\":\"145624\",\"isDeleted\":false,\"isValid\":\"1\",\"productName\":\"中小学幼儿园校方责任保险\",\"sameHolder\":\"1\",\"schoolProperty\":\"edu_03\",\"schoolType\":\"edu_06\",\"startDate\":\"2020-09-01\",\"status\":\"1\"}]";
            List<SxApplicationFormInfo> param = JSON.parseArray(a, SxApplicationFormInfo.class);
            sxApplicationFormService.downAppPdf(param, request, response);
        } catch (Exception e) {
            //log.error("生成投保单pdf失败,请稍后重试")xdc;
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "测试round", notes = "测试round", httpMethod = "GET")
    @GetMapping(value = "/selectInsBatch", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity selectInsBatch(HttpServletRequest request, HttpServletResponse response) {
        Weekend<InsBatchEntity> weekend = Weekend.of(InsBatchEntity.class);
        WeekendCriteria<InsBatchEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(InsBatchEntity::getHandleStatus, HandlerStatusEnum.NO_INS.getCode());
        criteria.andEqualTo(InsBatchEntity::getIsDeleted, IsOrNotEnum.NO.getValue());
        criteria.andLessThan(InsBatchEntity::getTimes, 6);
        //从第0位开始查询，查询出前300个
        RowBounds rowBounds = new RowBounds(0, 300);
        List<InsBatchEntity> resultList = insBatchEntityMapper.selectByExampleAndRowBounds(weekend, rowBounds);

        return GenericDataResponse.okWithData(resultList);
    }

    @Component
    class MyRunnable implements Runnable {

        private InsOrderClient insOrderClient;

        public MyRunnable(InsOrderClient insOrderClient) {
            this.insOrderClient = insOrderClient;
        }

        @Override
        public void run() {
            synchronized (this) {
                for (int i = 0; i < 5; i++) {
                    //往投保平台传值的时候需要重新拼对象
                    TOrderChargeQueryVO tOrderChargeQueryVO = new TOrderChargeQueryVO();
                    tOrderChargeQueryVO.setChargeNo("2313251106247673124");
                    tOrderChargeQueryVO.setConfirmDate("2020-09-15 17:24:22");
                    tOrderChargeQueryVO.setOrderCode("D2009151724086478941");
                    //转换支付对应的支付channel及code
                    tOrderChargeQueryVO.setPayChannel("weixin");
                    tOrderChargeQueryVO.setStatus("1");

                    log.info("参数：" + JsonUtils.toJson(tOrderChargeQueryVO));

                    //在支付过程中，有可能已经支付超时定时任务已经将投保中心的投保单状态修改成11(失效)，在这里检查并修正 回来
                    try {
                        ResponseEntity<GenericDataResponse<Map<String, String>>> a = insOrderClient.orderPay(tOrderChargeQueryVO);
                        log.info(JSON.toJSONString(a));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }


}
